import { defineStore } from 'pinia';  
import { ref } from 'vue';  
import { scanTrendsAddScore } from '@/utils/api/index.ts';  

export const useCounterStore = defineStore('counter', () => {  
  const mainCountdown = ref(60); // 主倒计时，单位：秒  
  const secondaryCountdown = ref(30); // 副倒计时，单位：秒，设置默认值  
  const isMainCountdownRunning = ref(false); // 主倒计时是否运行中  
  const isSecondaryCountdownRunning = ref(false); // 副倒计时是否运行中  
  let mainInterval = null; // 主倒计时 interval 引用  
  let secondaryInterval = null; // 副倒计时 interval 引用 
  // 启动主倒计时  
function startMainCountdown() {  
    if (isMainCountdownRunning.value) return; // 防止重复启动  
    isMainCountdownRunning.value = true;  
	console.log('执行定时器')
    mainInterval = setInterval(async () => {  
        if (mainCountdown.value > 0) {  
            mainCountdown.value--;
        } else {  
            clearInterval(mainInterval);  
            isMainCountdownRunning.value = false;  
            await callBackendApi(); // 主倒计时归零时调用后端接口  
        }  
    }, 1000);  
}

  // 启动副倒计时  
  function startSecondaryCountdown(duration = 30) {  
    if (isSecondaryCountdownRunning.value) return; // 防止重复启动  
    secondaryCountdown.value = duration; // 设置副倒计时  
    isSecondaryCountdownRunning.value = true;  

    secondaryInterval = setInterval(() => {  
      if (secondaryCountdown.value > 0) {  
        secondaryCountdown.value--;
      } else {  
        clearInterval(secondaryInterval);  
        isSecondaryCountdownRunning.value = false;  
        pauseMainCountdown(); // 暂停主倒计时，当副倒计时归零时  
      }  
    }, 1000);  
  }  

  // 暂停主倒计时  
  function pauseMainCountdown() {  
    if (mainInterval) {  
      clearInterval(mainInterval);  
      isMainCountdownRunning.value = false;  
    }  
  }  

  // 恢复（启动或继续）主倒计时  
  function resumeMainCountdown() {  
    if (!isMainCountdownRunning.value) {  
      // 如果主倒计时没有运行，则启动  
      startMainCountdown();  
    }  
  }  

  // 调用后端接口  
  async function callBackendApi() {  
    try {  
      const res = await scanTrendsAddScore();  
      // 检查接口返回值决定后续动作  
      if (res.data.action === 1) {  
        uni.showToast({  
          title: res.data.msg,  
          icon: 'none',  
        });  
        // 成功响应后重置倒计时  
        resetCountdowns();  
        // 恢复主倒计时和启用副倒计时  
        resumeMainCountdown();  
        startSecondaryCountdown(30);  
      }  
    } catch (error) {  
      console.error('Error calling backend API:', error);  
      uni.showToast({  
        title: '请求失败，请稍后再试',  
        icon: 'none',  
      });  
    }  
  }  

  // 停止主倒计时  
  function stopMainCountdown() {  
    if (mainInterval) {  
      clearInterval(mainInterval);  
      mainInterval = null;  
      isMainCountdownRunning.value = false;  
    }  
  }  

  // 停止副倒计时  
  function stopSecondaryCountdown() {  
    if (secondaryInterval) {  
      clearInterval(secondaryInterval);  
      secondaryInterval = null;  
      isSecondaryCountdownRunning.value = false;  
    }  
  }  

  // 启用副倒计时并恢复主倒计时  
function resetSecondaryAndResumeMain(duration = 30) {  
    if (isSecondaryCountdownRunning.value) {  
        stopSecondaryCountdown(); // 停止当前副倒计时  
    }  
    startSecondaryCountdown(duration); // 启动新副倒计时  
    resumeMainCountdown(); // 继续主倒计时  
}

  // 重置所有倒计时  
  function resetCountdowns() {  
    stopMainCountdown();  
    stopSecondaryCountdown();  
    mainCountdown.value = 60;  
    secondaryCountdown.value = 30; // 重置副倒计时为30秒  
    isMainCountdownRunning.value = false;  
    isSecondaryCountdownRunning.value = false;  
  }  

  // 返回状态和方法  
  return {  
    mainCountdown,  
    secondaryCountdown,  
    isMainCountdownRunning,  
    isSecondaryCountdownRunning,  
    startMainCountdown,
    startSecondaryCountdown,  
    resetSecondaryAndResumeMain,  
    resetCountdowns,  
  };  
});